package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.ProjectManager.PMTaskRequireDialog;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.event.dom.client.ChangeEvent;

public class PMAssignTask extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField
	Label lblProjectName;
	@UiField(provided = true)
	CellTable<ProjectTaskDTO> ctbTask = new CellTable<ProjectTaskDTO>();
	@UiField
	SimplePager pager;
	@UiField
	Button btnBack;
	@UiField Button btnAssignTask;
	@UiField ListBox cboParent;

	interface Binder extends UiBinder<Widget, PMAssignTask> {
	}
	final MultiSelectionModel<ProjectTaskDTO> selectionModel = new MultiSelectionModel<ProjectTaskDTO>();
	private List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();
	private final ProjectServiceAsync projectService = GWT
			.create(ProjectService.class);
	private String projectID;
	ProjectDTO currProject = new ProjectDTO();
	public PMAssignTask() {
		initWidget(binder.createAndBindUi(this));
		initTable();
		bindData();
	}

	public PMAssignTask(String projectId) {
		this.projectID = projectId;
		initWidget(binder.createAndBindUi(this));
		projectService.getProjectById(projectId,
				new AsyncCallback<ProjectDTO>() {

					@Override
					public void onSuccess(ProjectDTO result) {
						// TODO Auto-generated method stub
						currProject = result;
						lblProjectName.setText("Dự án : "
								+ result.getProjectName());
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
		initTable();
		bindData();
	}

	public void bindData() {
		projectService.getListTask(projectID,
				new AsyncCallback<List<ProjectTaskDTO>>() {

					@Override
					public void onSuccess(List<ProjectTaskDTO> result) {
						// TODO Auto-generated method stub
						cboParent.addItem("Tất cả","-1");
						cboParent.addItem("Không có công việc cha","-2");
						for (ProjectTaskDTO task : result) {
							if ((task.getSubTasks() == null || task
									.getSubTasks().equals(""))
									&& task.getIsMile() == 0 &&task.getStatus()!=3 &&task.getStatus()!=2) {
								listTask.add(task);
							}
							if(task.getGroup()==1)
							{
								cboParent.addItem(task.getTaskName(),task.getTaskId()+"");
							}

						}
						LoadDataForTable(listTask);
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("không thể load dữ liệu");
					}
				});

	}

	public void initTable() {

		ctbTask.setSelectionModel(selectionModel,
				DefaultSelectionEventManager
						.<ProjectTaskDTO> createCheckboxManager());
		Column<ProjectTaskDTO, Boolean> checkColumn = new Column<ProjectTaskDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(ProjectTaskDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		TextColumn<ProjectTaskDTO> stt = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO task) {
				return task.getSTT();
			}
		};


		TextColumn<ProjectTaskDTO> startDate = new TextColumn<ProjectTaskDTO>() {
			@SuppressWarnings("deprecation")
			@Override
			public String getValue(ProjectTaskDTO task) {
				Date startDate = new Date(task.getStartDate());
				return startDate.getDate() + "/" + (startDate.getMonth() + 1)
						+ "/" + (startDate.getYear() + 1900);
			}
		};
		TextColumn<ProjectTaskDTO> dueDate = new TextColumn<ProjectTaskDTO>() {
			@SuppressWarnings("deprecation")
			@Override
			public String getValue(ProjectTaskDTO task) {
				Date dueDate = new Date(task.getDueDate());
				return dueDate.getDate() + "/" + (dueDate.getMonth() + 1) + "/"
						+ (dueDate.getYear() + 1900);
			}
		};
		TextColumn<ProjectTaskDTO> amountOfWork = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO task) {
				return task.getAmountOfWork().toString() + " " + task.getUnit();
			}
		};

		TextColumn<ProjectTaskDTO> weight = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO task) {
				return task.getWeight().toString() + " %";
			}
		};

		Column<ProjectTaskDTO, String> taskNameColumn = new Column<ProjectTaskDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getTaskName();
			}
		};
		taskNameColumn
				.setFieldUpdater(new FieldUpdater<ProjectTaskDTO, String>() {

					@Override
					public void update(int index, ProjectTaskDTO task,
							String value) {
						// chuyển sang TaskReqDialog
						PMTaskRequireDialog dialog = new PMTaskRequireDialog(
								task, currProject);
						dialog.setPopupPosition(345, 100);
						dialog.show();
					}

				});

		TextColumn<ProjectTaskDTO> optName = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO task) {
				String name = "---";
				if (task.getOptAccountName() != null
						&& !task.getOptAccountName().equalsIgnoreCase("")) {
					name = task.getOptAccountName().toString();
				}
				return name;
			}
		};
		TextColumn<ProjectTaskDTO> status = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO task) {
				if (task.getStatus() == 0) {
					return "Chưa bắt đầu";
				}
				if (task.getStatus() == 1) {
					return "Đang tiến hành";
				}
				if (task.getStatus() == 2) {
					return "Đã hoàn thành";
				}
				if (task.getStatus() == 3) {
					return "Ngừng thực hiện";
				}
				return "";
			}
		};
		taskNameColumn.setCellStyleNames("celltable");

		ctbTask.setStyleName("ttable");
		ctbTask.addColumn(stt, "STT");
		ctbTask.setColumnWidth(stt, 4, Unit.PCT);
		ctbTask.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
		ctbTask.setColumnWidth(checkColumn, 4, Unit.PCT);
		ctbTask.addColumn(taskNameColumn, "Tên công việc");
		ctbTask.setColumnWidth(taskNameColumn, 25, Unit.PCT);
		ctbTask.addColumn(amountOfWork, "Khối lượng");
		ctbTask.setColumnWidth(amountOfWork, 10, Unit.PCT);
		ctbTask.addColumn(weight, "Trọng số");
		ctbTask.addColumn(optName, "Người thực hiện");
		ctbTask.addColumn(startDate, "Ngày bắt đầu");
		ctbTask.addColumn(dueDate, "Hạn kết thúc");
		ctbTask.addColumn(status, "Tình trạng");

	}

	public void LoadDataForTable(List<ProjectTaskDTO> taskList) {

		ListDataProvider<ProjectTaskDTO> dataProvider = new ListDataProvider<ProjectTaskDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbTask);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		// SimplePager
		pager.setDisplay(ctbTask);
		pager.setPageSize(5);
		int count = 1;
		List<ProjectTaskDTO> list = dataProvider.getList();
		for (ProjectTaskDTO task : taskList) {
			task.setSTT(count + "");
			count++;
			list.add(task);

		}
	}

	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		PMEntrypoint.get().callPop(projectID);
	}
	@UiHandler("btnAssignTask")
	void onBtnAssignTaskClick(ClickEvent event) {
		Boolean check = true;
		Set<ProjectTaskDTO> listChecked = selectionModel.getSelectedSet();
		List<ProjectTaskDTO> _listCheck = new ArrayList<ProjectTaskDTO>();
		if(listChecked.size()==0){
			Window.alert("Lựa chọn công việc trước khi gán người");
		}else{
			for (ProjectTaskDTO task : listChecked) {
			  if(task.getStatus()==0 || (task.getStatus()==1 && (task.getOptAccountName()==null)|| task.getOptAccountName().equalsIgnoreCase("")))
			    {
				  _listCheck.add(task);
			    
			    }else{
			    	check = false;
			    	Window.alert("Bạn không thể giao công việc đang tiến hành có người đảm nhiệm hoặc đã kết thúc hoặc bị tạm dừng!");
			       break;
			    }
			}
		}
		if(check && _listCheck.size()>0){
			AssignTaskToOptDialog dialog=new AssignTaskToOptDialog(currProject,_listCheck);
			dialog.setPopupPosition(545, 100);
			dialog.show();
			
		}
		selectionModel.clear();
	}
	@UiHandler("cboParent")
	void onCboParentChange(ChangeEvent event) {
		
		List<ProjectTaskDTO> listData = new ArrayList<ProjectTaskDTO>();
		String parentId=cboParent.getValue(cboParent.getSelectedIndex());
		for(ProjectTaskDTO  task :listTask )
		{
			if((task.getSubTasks() == null || task.getSubTasks().equals(""))&& task.getIsMile() == 0  &&task.getStatus()!=3 &&task.getStatus()!=2)
			{
				if(parentId.equals("-1") || parentId.equals(task.getParentId()+""))
				{
					listData.add(task);
				}
				
				if(parentId.equals("-2")&&task.getParentId()==0)
				{
					listData.add(task);
				}
			}
			
			
		}
		LoadDataForTable(listData);
		
	}
}
